<?php

include_once('logic/action/Action.php');
include_once('logic/view/update_view.php');

class UpdateAction extends Action
{
	public function perform()
	{
		$Photos = new PhotosDAO();
		$Tags   = new TagsDAO();
		$View   = new UpdateView();

		if (Session::getSessionVar ("logged_in") == 'true')
		{
			$View->setParam('_user_logged_in', 'true');
			// photo id
			$photoId = HttpRequest::getRequest('id');
			$formPosted = HttpRequest::getRequest('form_posted');

			// if there was no form post we just fill in form data
			if ($formPosted == '' && $Photos->isExisting($photoId))
			{
				$View->setParam('_id', $photoId);
				$View->setParam('_title', $Photos->getTitle($photoId));
				$View->setParam('_date', $Photos->getSubmitDate($photoId));
				$View->setParam('_description', $Photos->getDescription($photoId));

				$tmp = "";
				$tagsArray = $Tags->getTags($photoId);
				foreach ($tagsArray as $tag)
				{
					if ($tmp != '') $tmp .= ', ';
					$tmp .= $tag[0];
				}
				$View->setParam('_tags', $tmp);
			}
			// check if there was a post
			else if ($formPosted == 'posted')
			{
				// get values
				$title = HttpRequest::getRequest('title');
				$date = HttpRequest::getRequest('date');
				$description = HttpRequest::getRequest('description');
				$tags = HttpRequest::getRequest('tags');

				$valid = true;

				// title is not empty
				if (Validator::isEmpty($title))
				{
					$View->setParam('_title_empty_error', 'true');
					$valid = false;
				}

				// date empty
				if (Validator::isEmpty($date))
				{
					$View->setParam('_date_empty_error', 'true');
					$valid = false;
				}

				// date format is wrong
				if (!Validator::isDate($date))
				{
					$View->setParam('_date_format_error', 'true');
					$valid = false;
				}

				// fill back common things
				$View->setParam('_title', $title);
				$View->setParam('_description', $description);
				$View->setParam('_date', $date);

				if ($valid)
				{
					// delete all old tags
					$Tags->deleteAllTags($photoId);

					// reinsert the new ones
					$tagsArray = explode(',', $tags);
					$filteredTags = "";
					foreach ($tagsArray as $tag)
					{
						$tmp = trim($tag);
						if ($tmp != "")
						{
							$Tags->addTag($photoId, trim($tmp));

							// build new tag list (filter out separators)
							if ($filteredTags != '') $filteredTags .= ', ';
							$filteredTags .= $tmp;
						}
					}
					$View->setParam('_tags', $filteredTags);

					$Photos->updateTitle($photoId, $title);
					$Photos->updateSubmitDate($photoId, $date);
					$Photos->updateDescription($photoId, $description);

					$View->setParam('_entry_updated', 'true');
				}
			}
		} else {
			$View->setParam('_user_logged_in', 'false');
		}

		parent::setCommonParams($View);
		$View->display();
	}
}

?>
